// filename: server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#define FIFO_PATH "/tmp/myfifo"
int main() {
    // 创建命名管道（如果不存在的话）
    if (mkfifo(FIFO_PATH, 0666) < 0 && errno != EEXIST) {
        perror("Failed to create named pipe");
        exit(EXIT_FAILURE);
    }
    // 打开命名管道用于读取
    int fifo_fd = open(FIFO_PATH, O_RDONLY);
    if (fifo_fd == -1) {
        perror("Failed to open named pipe for reading");
        exit(EXIT_FAILURE);
    }
    char buffer[255];
    while (1) {
        ssize_t bytes_read = read(fifo_fd, buffer, sizeof(buffer) - 1);
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';
            printf("Received: %s\n", buffer);
        } else if (bytes_read == 0) {
            printf("Writer closed the connection.\n");
            break;
        } else if (errno != EAGAIN) {
            perror("Read error");
            break;
        }
    }
    // 关闭管道文件描述符
    close(fifo_fd);
    unlink(FIFO_PATH); // 可选：使用完毕后删除命名管道文件
    return 0;
}